package Semaphore_8;
import java.util.concurrent.Semaphore;
public class 基础用法_控制资源并发访问 {
    public static void main(String[] args) {
        final int THREAD_COUNT = 20;
        final Semaphore semaphore = new Semaphore(3); // 允许3个线程同时访问
        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println("线程-" + threadId + " 尝试获取许可");
                        semaphore.acquire();

                        System.out.println("线程-" + threadId + " 获得许可，开始访问资源");
                        Thread.sleep((long)(Math.random() * 1000 + 500)); // 模拟资源访问

                        System.out.println("线程-" + threadId + " 释放许可");
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}